//
//  CustomUITextView.m
//  CPACommunity
//
//  Created by Mac on 13-1-15.
//  Copyright (c) 2013年 Mac. All rights reserved.
//

#import "CustomUITextView.h"

@implementation CustomUITextView

@synthesize placeholder,placeholderColor,placeHolderFont;

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];    
    self.placeholder = nil;
    self.placeholderColor = nil;
    self.placeHolderFont = nil;
    [placeHolderLabel release];
    
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    if( (self = [super initWithFrame:frame]) )
    {
        [self setPlaceholder:@""];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

- (void)textChanged:(NSNotification *)notification
{
    if([[self placeholder] length] == 0)
    {
        return;
    }
    
    if([[self text] length] == 0)
    {
        [[self viewWithTag:999] setAlpha:1];
    }
    else
    {
        [[self viewWithTag:999] setAlpha:0];
    }
}

- (void)setText:(NSString *)text {
    [super setText:text];
    [self textChanged:nil];
}

- (void)drawRect:(CGRect)rect
{
    if( [[self placeholder] length] > 0 )
    {
        if (placeHolderLabel == nil )
        {
            placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(8.0,7.0,self.bounds.size.width-16,0)];
            placeHolderLabel.lineBreakMode = UILineBreakModeWordWrap;
            placeHolderLabel.numberOfLines = 0;
            placeHolderLabel.backgroundColor = [UIColor clearColor];
            placeHolderLabel.textColor = placeholderColor;
            placeHolderLabel.alpha = 0;
            placeHolderLabel.tag = 999;
            placeHolderLabel.font = placeHolderFont;
            [self addSubview:placeHolderLabel];
        }
        
        placeHolderLabel.text = placeholder;
        [placeHolderLabel sizeToFit];
        [self sendSubviewToBack:placeHolderLabel];
    }
    
    if( [[self text] length] == 0 && [[self placeholder] length] > 0 )
    {
        [[self viewWithTag:999] setAlpha:1];
    }
    
    [super drawRect:rect];
}


//设置提示语言属性
-(void)setTip:(NSString*)tip font:(UIFont*)font color:(UIColor*)color
{
    self.placeholder = tip;
    self.placeHolderFont = font;
    self.placeholderColor = color;
}

@end
